<template>
  <div class="page-container">
    <div class="page-header">
      <h2>客户管理</h2>
      <p>管理系统中的所有客户信息</p>
    </div>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="公司名称">
          <el-input 
            v-model="searchForm.companyName" 
            placeholder="请输入公司名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input 
            v-model="searchForm.contactPerson" 
            placeholder="请输入联系人"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户等级">
          <el-select 
            v-model="searchForm.customerLevel" 
            placeholder="请选择客户等级"
            clearable
            style="width: 140px"
          >
            <el-option label="A级" value="A" />
            <el-option label="B级" value="B" />
            <el-option label="C级" value="C" />
            <el-option label="D级" value="D" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属行业">
          <el-input 
            v-model="searchForm.industry" 
            placeholder="请输入所属行业"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 工具栏 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新增客户
        </el-button>
        <el-button 
          type="danger" 
          :disabled="!selectedIds.length"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      stripe
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="customerCode" label="客户编号" width="120" />
      <el-table-column prop="companyName" label="公司名称" min-width="150" />
      <el-table-column prop="contactPerson" label="联系人" width="100" />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column prop="mobile" label="手机号码" width="120" />
      <el-table-column prop="industry" label="所属行业" width="100" />
      <el-table-column prop="customerLevel" label="客户等级" width="80">
        <template #default="{ row }">
          <span :class="`level-tag ${row.customerLevel}`">{{ row.customerLevel }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="province" label="省份" width="80" />
      <el-table-column prop="city" label="城市" width="80" />
      <el-table-column prop="customerSource" label="客户来源" width="100" />
      <el-table-column prop="createdAt" label="创建时间" width="160">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleView(row)">
            <el-icon><View /></el-icon>
            查看
          </el-button>
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        :disabled="dialogMode === 'view'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编号" prop="customerCode">
              <el-input v-model="formData.customerCode" placeholder="请输入客户编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="省份" prop="province">
              <el-input v-model="formData.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="城市" prop="city">
              <el-input v-model="formData.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区县" prop="district">
              <el-input v-model="formData.district" placeholder="请输入区县" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industry">
              <el-input v-model="formData.industry" placeholder="请输入所属行业" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户等级" prop="customerLevel">
              <el-select v-model="formData.customerLevel" placeholder="请选择客户等级">
                <el-option label="A级" value="A" />
                <el-option label="B级" value="B" />
                <el-option label="C级" value="C" />
                <el-option label="D级" value="D" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户来源" prop="customerSource">
              <el-input v-model="formData.customerSource" placeholder="请输入客户来源" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input 
                v-model="formData.remark" 
                type="textarea" 
                :rows="3"
                placeholder="请输入备注信息" 
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div v-if="dialogMode === 'view'">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
        <div v-else>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  getCustomers, 
  createCustomer, 
  updateCustomer, 
  deleteCustomer,
  batchDeleteCustomers 
} from '@/api/customers'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const submitLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  companyName: '',
  contactPerson: '',
  customerLevel: '',
  industry: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref('create') // create, edit, view
const formRef = ref()

// 表单数据
const formData = reactive({
  id: null,
  customerCode: '',
  companyName: '',
  contactPerson: '',
  phone: '',
  mobile: '',
  email: '',
  address: '',
  province: '',
  city: '',
  district: '',
  industry: '',
  customerLevel: 'C',
  customerSource: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  customerCode: [
    { required: true, message: '请输入客户编号', trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    create: '新增客户',
    edit: '编辑客户',
    view: '查看客户'
  }
  return titles[dialogMode.value]
})

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    const response = await getCustomers(params)
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        tableData.value = responseData.data
        pagination.total = responseData.total || 0
        console.log('成功加载客户数据:', responseData.data.length, '条')
      } else if (responseData && Array.isArray(responseData)) {
        tableData.value = responseData
        pagination.total = responseData.length
      } else {
        console.warn('API返回的数据格式不正确:', responseData)
        tableData.value = []
        pagination.total = 0
      }
    }
  } catch (error) {
    console.error('获取客户列表失败:', error)
    // 使用模拟数据
    tableData.value = [
      {
        id: 1,
        customerCode: 'CUS001',
        companyName: '北京科技有限公司',
        contactPerson: '张总',
        phone: '010-12345678',
        mobile: '13888888888',
        email: 'zhang@bjtech.com',
        address: '北京市朝阳区科技园区1号',
        province: '北京市',
        city: '北京市',
        district: '朝阳区',
        industry: 'IT科技',
        customerLevel: 'A',
        customerSource: '网络推广',
        remark: '重要客户，年采购量大',
        createdAt: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        customerCode: 'CUS002',
        companyName: '上海贸易公司',
        contactPerson: '李经理',
        phone: '021-87654321',
        mobile: '13999999999',
        email: 'li@shtrade.com',
        address: '上海市浦东新区金融街88号',
        province: '上海市',
        city: '上海市',
        district: '浦东新区',
        industry: '贸易',
        customerLevel: 'B',
        customerSource: '客户推荐',
        remark: '稳定合作伙伴',
        createdAt: '2024-01-14 14:20:00'
      }
    ]
    pagination.total = 2
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getTableData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    companyName: '',
    contactPerson: '',
    customerLevel: '',
    industry: ''
  })
  handleSearch()
}

// 新增
const handleCreate = () => {
  dialogMode.value = 'create'
  resetFormData()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogMode.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  dialogMode.value = 'view'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除客户"${row.companyName}"吗？`, '确认删除', {
      type: 'warning'
    })
    
    await deleteCustomer(row.id)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}个客户吗？`, '确认删除', {
      type: 'warning'
    })
    
    await batchDeleteCustomers(selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}


// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.page = 1
  getTableData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.page = val
  getTableData()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    if (dialogMode.value === 'create') {
      await createCustomer(formData)
      ElMessage.success('新增成功')
    } else {
      await updateCustomer(formData.id, formData)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    getTableData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 弹窗关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
  dialogVisible.value = false
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    customerCode: '',
    companyName: '',
    contactPerson: '',
    phone: '',
    mobile: '',
    email: '',
    address: '',
    province: '',
    city: '',
    district: '',
    industry: '',
    customerLevel: 'C',
    customerSource: '',
    remark: ''
  })
}

// 页面初始化
onMounted(() => {
  getTableData()
})
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }
  
  p {
    color: #666;
    font-size: 14px;
  }
}
</style> 